package store.lunangangster.engine.impl.repository;

import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultDeploymentCache<T> implements DeploymentCache<T> {

  private static final Logger log = LoggerFactory.getLogger(DefaultDeploymentCache.class);

  protected int limit;
  protected int size;
  protected Map<String, T> cache;

  public DefaultDeploymentCache() {
    this.size = 0;
    cache = new LinkedHashMap<>();
  }

  public DefaultDeploymentCache(int limit) {
    this.limit = limit;
    this.size = 0;
    if (limit <= 0) {
      cache = new LinkedHashMap<>();
    } else {
      // why limit + 1 : 创建HashMap时，会找到比initialCapacity大的最近的一个2^n作为容量。+1保证当limit为2的幂时，创建时就进行一次扩容
      cache = new LinkedHashMap<String, T>(limit + 1, 0.75f, true) {
        // LRU
        @Override
        protected boolean removeEldestEntry(Map.Entry eldest) {
          boolean removeEldestEntry = size() > limit;
          log.debug("DefaultDeploymentCache已满，进行LRU");
          return removeEldestEntry;
        }
      };
    }
  }

  @Override
  public T get(String key) {
    return cache.get(key);
  }

  @Override
  public void set(String key, T value) {
    if (value != null) {
      if (!contains(key)) {
        size++;
      }
      cache.put(key, value);
    }
  }

  @Override
  public boolean contains(String key) {
    if (cache.containsKey(key)) {
      return cache.get(key) != null;
    }
    return false;
  }

  @Override
  public void remove(String key) {
    if (cache.containsKey(key)) {
      size--;
    }
    cache.remove(key);
  }

  @Override
  public void clear() {
    cache.clear();
    size = 0;
  }
}
